package cn.wen.eeayjoke.ui.pager;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Created by Administrator on 2018/7/7.
 */

public class MyRecyclerView extends RecyclerView {
    private float downY;

    public MyRecyclerView(Context context) {
        super(context);
    }

    public MyRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                float dy = ev.getY() - downY;
                //滑动到顶部让父控件重新获得触摸事件
                if (dy > 0 && !canScrollUp()) {
                    getParent().requestDisallowInterceptTouchEvent(false);
                    return false;
                } else if (dy < 0 && !canScrollDown()) {
                    getParent().requestDisallowInterceptTouchEvent(false);
                    return false;
                } else {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                break;
            case MotionEvent.ACTION_DOWN:
                getParent().requestDisallowInterceptTouchEvent(true);
                this.downY = ev.getY();
                break;


        }
        return super.onInterceptTouchEvent(ev);
    }

    /**
     * @return Whether it is possible for the child view of this layout to
     * scroll up. Override this if the child view is a custom view.
     * 判断是不是滚动到了最顶部，这个是从SwipeRefreshLayout里面copy过来的源代码
     */
    public boolean canScrollDown() {
        return canScrollVertically(1);
    }

    /**
     * 判断是不是滚动到了最顶部，这个是从SwipeRefreshLayout里面copy过来的源代码
     */
    private boolean canScrollUp() {

        if (android.os.Build.VERSION.SDK_INT < 14) {
            return (canScrollVertically(-1) || this.getScrollY() > 0);
        } else {
            return canScrollVertically(-1);
        }
    }
}
